﻿/**
 * searchdialog - jQuery EasyUI
 * 
 * Auth:Mark
 * 
 * Dependencies:
 *   dialog
 *   datagrid
 * 
 */
(function ($) {
    /**
	 * 创建组建
	 */
    function create(target) {
        var state = $.data(target, 'searchdialog'), opts = state.options, grid = state.grid, data = state.data, searchMenu, editIndex;
        $(target).addClass('searchdialog-f').dialog(opts);
        var panel = $(target).find('.panel-body');
        if (!grid) {
            grid = $('<table></table>').appendTo(panel);
            state.grid = grid;
        }

        grid.datagrid({
            border: false,
            fit: true,
            fitColumns: true,
            columns: [[
                { field: 'title', title: '属性', width: 100 },
                {
                    field: 'method', title: '运算符', width: 100, formatter: methodFormatter, editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'value',
                            textField: 'text',
                            data: [{
                                text: '等于',
                                value: 'Equal'
                            }, {
                                text: '小于',
                                value: 'LessThan'
                            }, {
                                text: '大于',
                                value: 'GreaterThan'
                            }, {
                                text: '小于等于',
                                value: 'LessThanOrEqual'
                            }, {
                                text: '大于等于',
                                value: 'GreaterThanOrEqual'
                            }, {
                                text: '不等于',
                                value: 'NotEqual'
                            }, {
                                text: '开头等于',
                                value: 'StartsWith'
                            }, {
                                text: '结尾等于',
                                value: 'EndsWith'
                            }, {
                                text: '包含',
                                value: 'Contains'
                            }]
                        }
                    }
                },
                { field: 'value', title: '值', width: 100, formatter: valueFormatter, editor: { type: 'text' } }
            ]],
            singleSelect: true,
            onClickCell: function (index, field) {
                if (endEditing(grid,editIndex)) {
                    grid.datagrid('selectRow', index)
                            .datagrid('editSearchGridCell', { index: index, field: field });
                    editIndex = index;
                }
            },
            onRowContextMenu: function (e, field) {
                e.preventDefault();
                if (!searchMenu) {
                    createMenu();
                }
                searchMenu.menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            }
        });

        /**
	     * 创建菜单
	     */
        function createMenu() {
            searchMenu = $('<div><div>添加</div></div>').appendTo('body');
            searchMenu.menu({
                onClick: function (item) {
                    grid.datagrid('appendRow', {
                        field: item.name,
                        title: item.text,
                        method: 'Equal'
                    });
                }
            });

            data = $.data(target, 'searchdialog').data;
            var item = searchMenu.menu('findItem', '添加');
            for (var i = 0; i < data.length; i++) {
                var currData = data[i];
                searchMenu.menu('appendItem', {
                    parent: item.target,
                    text: currData.title,
                    name: currData.field
                });
            }
        }

        /**
	     * 值格式化
	     */
        function valueFormatter(value, row, index) {
            return row.valueStr || value;
        }

        /**
	     * 运算符格式化
	     */
        function methodFormatter(value, row, index) {
            var result = '';
            switch (value) {
                case 'Equal':
                    result = '等于';
                    break;
                case 'LessThan':
                    result = '小于';
                    break;
                case 'GreaterThan':
                    result = '大于';
                    break;
                case 'LessThanOrEqual':
                    result = '小于等于';
                    break;
                case 'GreaterThanOrEqual':
                    result = '大于等于';
                    break;
                case 'NotEqual':
                    result = '不等于';
                    break;
                case 'StartsWith':
                    result = '开头等于';
                    break;
                case 'EndsWith':
                    result = '结尾等于';
                    break;
                case 'Contains':
                    result = '包含';
                    break;
                default:
            }
            return result;
        }
    }

    /**
     * 停止编辑
     */
    function endEditing(grid, editIndex) {
        if (editIndex == undefined) { return true }


        var ed = grid.datagrid('getEditor', {
            index: editIndex,
            field: 'value'
        });

        if (ed && ed.type == 'combotree') {
            var row = grid.datagrid('getRows')[editIndex];
            row.valueStr = $(ed.target).combotree('getText');
        }

        grid.datagrid('endEdit', editIndex);
        editIndex = undefined;
        return true;
    }

    /**
	* 加载数据
	*/
    function loadData(target, data) {
        var state = $.data(target, 'searchdialog');
        state.data = data;
        $.data(target, 'searchdialog', state);
        $(target).searchdialog('grid').datagrid('loadData', data);
    }

    $.fn.searchdialog = function (options, param) {
        if (typeof options == 'string') {
            var method = $.fn.searchdialog.methods[options];
            if (method) {
                return method(this, param);
            } else {
                return this.dialog(options, param);
            }
        }

        options = options || {};
        return this.each(function () {
            var state = $.data(this, 'searchdialog');
            if (state) {
                $.extend(state.options, options);
            } else {
                state = $.data(this, 'searchdialog', {
                    options: $.extend({}, $.fn.searchdialog.defaults, $.fn.searchdialog.parseOptions(this), options)
                });
            }

            create(this);
        });
    };

    $.fn.searchdialog.methods = {
        options: function (jq) {
            return $.data(jq[0], 'searchdialog').options;
        },
        grid: function (jq) {
            return $.data(jq[0], 'searchdialog').grid;
        },
        loadData: function (jq, data) {
            return jq.each(function () {
                loadData(this, data);
            });
        },
        getQueryParams: function (jq) {
            var grid = $(jq[0]).searchdialog('grid');
            var selected = grid.datagrid('getSelected');
            if (selected) {
                var rowIndex = grid.datagrid('getRowIndex', selected);
                endEditing(grid, rowIndex);
            }

            var data = $(jq[0]).searchdialog('grid').datagrid('getData');
            var queryParams = {};

            var rows = data.rows;
            for (var i = 0; i < rows.length; i++) {
                var field = rows[i].field, method = rows[i].method, value = rows[i].value, expression;
                if (!value) {
                    continue;
                }
                expression = '[' + method + ']' + field
                queryParams[expression] = value;
            }

            return queryParams;
        }
    };

    $.fn.searchdialog.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.fn.dialog.parseOptions(target), $.fn.datagrid.parseOptions(target),
                $.parser.parseOptions(target, ['idField', 'textField', 'mode']));
    };

    $.fn.searchdialog.defaults = $.extend({}, $.fn.dialog.defaults, $.fn.datagrid.defaults, {
        width: 600,
        height: 300,
        toolbar: [{
            text: '清空',
            iconCls: 'icon-reload',
            handler: function () {
                alert('clear');
            }
        }, {
            text: '查询',
            iconCls: 'icon-save',
            handler: function () {
                alert('search')
            }
        }],
        closable: true,
        onClickSearch: function (queryParams) { }
    });




})(jQuery);
